package jp.co.worksap.ate.gomoku.hadoopai;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import jp.co.worksap.ate.gomoku.model.GoState;
import jp.co.worksap.ate.gomoku.model.Goban;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;

public class GobanParam implements Writable {
	private Goban goban;
	private IntWritable x = new IntWritable();
	private IntWritable y = new IntWritable();
	private IntWritable level = new IntWritable();
	private IntWritable xSize = new IntWritable();
	private IntWritable ySize = new IntWritable();
	private IntWritable type = new IntWritable();
	@Override
	public void readFields(DataInput in) throws IOException {
		x.readFields(in);
		y.readFields(in);
		level.readFields(in);
		xSize.readFields(in);
		ySize.readFields(in);
		type.readFields(in);
		int xLen = xSize.get();
		int yLen = ySize.get();
		goban = new Goban(xLen, yLen);
		for(int i=0; i<xLen; i++) {
			for(int j=0; j<yLen; j++) {
				IntWritable goIntWritable = new IntWritable();
				goIntWritable.readFields(in);
				int goInt = goIntWritable.get();
				switch(goInt) {
				case -1: goban.putBlack(i, j); break;
				case 1: goban.putWhite(i, j); break;
				}
			}
		}
	}

	@Override
	public void write(DataOutput out) throws IOException {
		// TODO Auto-generated method stub
		x.write(out);
		y.write(out);
		level.write(out);
		xSize.write(out);
		ySize.write(out);
		type.write(out);
		int xLen = xSize.get();
		int yLen = ySize.get();
		for(int i=0; i<xLen; i++) {
			for(int j=0; j<yLen; j++) {
				IntWritable goIntWritable = new IntWritable();
				switch(goban.getGoState(i, j)) {
				case BLACK: goIntWritable.set(-1); break; 
				case EMPTY: goIntWritable.set(0); break; 
				case WHITE: goIntWritable.set(1); break; 
				}
				goIntWritable.write(out);
			}
		}
	}

	public Goban getGoban() {
		return goban;
	}

	public void setGoban(Goban goban) {
		this.goban = goban;
		xSize.set(goban.getXSize());
		ySize.set(goban.getYSize());
	}

	public GoState getGoType() {
		int typeInt = type.get();
		if(typeInt<0) {
			return GoState.BLACK;
		} else if (typeInt==0){
			return GoState.EMPTY;
		} else {
			return GoState.WHITE;
		}
	}

	public void setGoType(GoState goType) {
		switch(goType) {
		case BLACK: this.type.set(-1); break; 
		case EMPTY: this.type.set(0); break; 
		case WHITE: this.type.set(1); break; 
		}
	}

	public int getX() {
		return x.get();
	}

	public void setX(int x) {
		this.x.set(x);
	}

	public int getY() {
		return y.get();
	}

	public void setY(int y) {
		this.y.set(y);
	}

	public int getLevel() {
		return level.get();
	}

	public void setLevel(int level) {
		this.level.set(level);
	}

}
